using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace MapReduce.Comm
{
    public static class Slave
    {
        private static Object mLockObj = new Object();

        private static String mListenTo;
        private static ushort mPort;

        public static String Address { get { return mListenTo; } }
        public static ushort Port { get { return mPort; } }


        public static void Start(String pListenTo, ushort pPort)
        {
            mListenTo = pListenTo;
            mPort = pPort; 
            
            Thread t = new Thread(ThreadedStart);
            t.Start();

        }
        private static void ThreadedStart()
        {

            IPAddress ipAd = IPAddress.Parse(mListenTo); //use local m/c IP address, and use the same in the client

            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAd, mPort);

            /* Start Listeneting at the specified port */
            myList.Start();
            try
            {

                //U.Log("The server is running at port " + mPort + "...");
                //U.Log("Listening On :" + myList.LocalEndpoint);
                //U.Log("Waiting for a connection.....");


                while (true)
                {
                    lock (mLockObj)
                    {
                        Socket s = myList.AcceptSocket();
                        SocketThread thread = new SocketThread(s, myList, mListenTo, mPort);
                        thread.Start();
                    }
                }



            }
            finally
            {

                myList.Stop();

            }
        }//Start



    }//Slave
}
